package top.jiangqiang.qyblog.core.storage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.UriUtils;
import software.amazon.awssdk.awscore.AwsClient;
import top.jiangqiang.qyblog.common.config.GlobalProperties;
import top.jiangqiang.qyblog.core.domain.StorageProperties;
import top.jiangqiang.qyblog.core.domain.entity.Storage;

import java.nio.charset.StandardCharsets;

/**
 * @author Jiangqiang
 * @version 1.0
 * @date 2022/12/7 14:23
 */
@Slf4j
public abstract class AbstractS3StorageClient<T extends AwsClient> implements StorageClient {
    protected T client;
    @Getter
    protected final Storage storage;
    protected final StorageProperties properties;
    //新增存储器配置时，对配置进行校验时此字段没有值
    protected final Long storageId;
    //缓存目录
    @Getter
    protected final java.io.File cacheDir;
    protected final GlobalProperties globalProperties;

    public AbstractS3StorageClient(Storage storage, GlobalProperties globalProperties) {
        this.storage = storage;
        this.properties = storage.getConfig();
        this.storageId = storage.getId();
        this.globalProperties = globalProperties;
        this.cacheDir = FileUtil.file(globalProperties.getFileConfig().getCachePath());
    }

    @Override
    public String getUrl(String fileKey) {
        String objectURL;
        if (StringUtils.isBlank(properties.getDomain())) {
            String host;
            if (properties.getEnablePathStyleAccess()) {
                host = properties.getEndpoint() + "/" + properties.getBucket();
            } else {
                host = properties.getBucket() + "." + properties.getEndpoint();
            }
            objectURL = properties.getAccessProtocol() + "://" + host + "/" + fileKey;
        } else {
            objectURL = properties.getAccessProtocol() + "://" + properties.getDomain() + "/" + fileKey;
        }
        return UriUtils.encodePath(objectURL, StandardCharsets.UTF_8);
    }

    @Override
    public void close() {
        log.debug("关闭当前存储器，存储器配置:{}", properties);
        IoUtil.close(this.client);
    }

}
